<script>
	import chatInput from './chatinput.vue';
	import messageShow from './messageshow.vue';
	import { requestURL } from '@/common/utils/config.js';
	import { getToken } from '@/common/utils/auth.js';
	export default {
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [{
					user: 'home',
					type: 'head', //input,content 
					content: '你好!'
				}],
				type:''
			}
		},
		components: {
			chatInput,
			messageShow
		},
		onLoad(options) {
			
			if(options.type=='AI'){
				this.type='中国医科大学附属医院智能导诊';
			}
			if(options.type=='AR'){
				this.type='中国医科大学附属医院在线就诊';
			}	
		},
		created: function () { 
			
			this.initWebSocket();
			
			
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 410 * (100); //像素
		},
		methods: {
			getInputMessage: function (message) { //获取子组件的输入数据
				// console.log(message);
				this.addMessage('customer', message.content, false);
				this.toRobot(message.content);
			},
			addMessage: function (user, content, hasSub, subcontent) {
				var that = this;
				that.messages.push({
					user: user,
					content: content,
					hasSub: hasSub,
					subcontent: subcontent
				});
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();

				query.exec(function (res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function (rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					});

					if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
					}
				});
			},
			toRobot: function (info) {
				var user = 'person1';
				var respondent;
				console.log(this.type);
				if(this.type=='中国医科大学附属医院智能导诊'){
					respondent='AI';
				}
				if(this.type=='中国医科大学附属医院在线就诊'){
					respondent='AR';
				}
				
				var apiUrl = requestURL+'chat/getMessage?info='+info+'&user='+user+'&respondent='+respondent;
				console.log(apiUrl);
				var that = this
				uni.request({
					url: apiUrl,
					method:'get',
					header: {
						// 'Content-Type': 'applicatioin/json;charset=UTF-8', // 此处报错
						'Authorization': getToken() || ''
					},
					success: (res) => {
						console.log(res.data);
						if(res.data!=""){
							that.addMessage('home', res.data, false);
							that.scrollToBottom();
						}
					},
					fail: (err) => {
						console.log('request fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						})
					}
				});
			},
			initWebSocket: function () {
			  var user = 'person1';
			  var that = this
				// #ifdef MP-WEIXIN
					wx.connectSocket({
					 url: "ws://localhost:8002/websocket/"+user,
					 success() {
					  console.log('连接成功')
					  that.initEventHandle()
					 }
					})
				// #endif
				// #ifdef H5
					this.websock = new WebSocket("ws://localhost:8002/websocket/"+user);
					  this.websock.onopen = this.websocketonopen;
					  this.websock.onerror = this.websocketonerror;
					  this.websock.onmessage = this.websocketonmessage;
					  this.websock.onclose = this.websocketclose;
				// #endif
			 
			},
			initEventHandle(){
				var that = this
			  wx.onSocketMessage((res) => {
			   var da = res.data;
			   console.log(da);
			   that.addMessage('home', da, false);
			   that.scrollToBottom();
			  })
			  wx.onSocketOpen(()=>{
			   console.log('WebSocket连接打开')
			  })
			  wx.onSocketError(function (res) {
			   console.log('WebSocket连接打开失败')
			  })
			  wx.onSocketClose(function (res) {
			   console.log('WebSocket 已关闭！')
			  })
			 },
			        websocketonopen: function () {
			          console.log("WebSocket  open");
			        },
			        websocketonerror: function (e) {
			          console.log("WebSocket error");
			        },
			        websocketonmessage: function (e) {
			          var da = e.data;
			          console.log(da);
			          this.addMessage('home', da, false);
			          this.scrollToBottom();
			        },
			        websocketclose: function (e) {
			           console.log("connection closed ");
			        }
			
		},
		destroyed() {
			
			// #ifdef MP-WEIXIN
			wx.onSocketClose(function (res) {
			 console.log('WebSocket 已关闭！')
			})
			// #endif
			// #ifdef H5
			this.websocketclose();
			// #endif
		}
	}
</script>
<template>
	<view class="uni-column">
		<view class="head">	
		<span class ="header-span">{{type}}</span>
		</view>
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview"   scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			    :scroll-top="scrollTop">
				<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" v-bind:type="type" :id="index"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">
			<chat-input @send-message="getInputMessage" ></chat-input>
		</view>
	</view>
</template>

<style>
	.header-span{
		color: #FFFFFF;
		font-size: 18px;
		margin-top: 10px;
		margin-left: 15%;
	}
	.head{
		height: 45px;
		width: auto;
		background-color: #7ec0ee;
		font-weight:900;
	}
	.uni-column {
		display: flex;
		flex-direction: column;
	}
	.content {
		
		display: flex;
		flex: 1;
		margin-bottom: 100px;
		 
	}
	.foot {
		position: fixed;
		width: 100%;
		height: 45px;
		min-height: 45px;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
	}
</style>
